<?php


namespace api\contest\controller;


use app\dcp\manager\CenterManager;
use app\dcp\manager\VoteManager;
use app\wxoa\service\TemplateMessageService;
use think\model\concern\TimeStamp;

class SchoolMessageController
{
    /**
     * 功    能:学校提交作品即将截止通知
     */
    public function schoolSubmissionsEnd()
    {
        set_time_limit(0);
        ini_set('memory_limit', -1);
        $nowTimeStr = nowTimeStr();
        $where = [
            'a.submit_work_status' => 0, // 学校作品已提交
            'a.publish_status' => 1, // 活动已发布
            'a.deleted' => 0,
            'b.deleted' => 0
        ];
        $contestSchoolApply = (new \app\common\model\ContestSchoolApplyModel)->alias('a')
            ->join('wechat_contest b', 'a.contest_id = b.id', 'left')
            ->where($where)
            ->field('a.id schoolApplyId, a.contest_id contestId, a.inst_id instId, a.domain, b.name contestName, b.school_submit_end_time schoolSubmitEndTime')
            ->select()
            ->toArray();
        if (count($contestSchoolApply) > 0) {
            foreach ($contestSchoolApply as $key => &$value) {
                // 提前一天通知
                $timeDiff = $this->timeDifferenceCalculation(strtotime($value['schoolSubmitEndTime']), strtotime($nowTimeStr));
                if ($timeDiff !== 1) continue;
                $formatAppMessageByMethod = $this->formatAppMessageByMethod(__FUNCTION__, ['contestName' => $value['contestName']]);
                VoteManager::sendAppNotice($value['domain'], $value['instId'], $formatAppMessageByMethod['userData'], $formatAppMessageByMethod['content']);
                $instInfo = CenterManager::getInstInfoNewByInstId($value['domain'], $value['instId']);
                $instName = $instInfo['institution']['title'] ?? '';
                $formatWechatMessageByMethod = $this->formatWechatMessageByMethod(__FUNCTION__, ['contestName' => $value['contestName'], 'instName' => $instName]);
                TemplateMessageService::sendMessage($formatWechatMessageByMethod['userData'], 'workSubmissionDeadlineTemplate', $formatWechatMessageByMethod['templateData']);
            }
        }
        echo 'ok';
    }

    /**
     * 功    能:投票开始通知
     */
    public function vateStartNotification()
    {
        set_time_limit(0);
        ini_set('memory_limit', -1);
        $nowTimeStr = nowTimeStr();
        $where = [
            'a.submit_work_status' => 1, // 学校作品已提交
            'a.publish_status' => 1, // 活动已发布
            'b.vote_open' => 1, // 投票开关已开启
            'b.end_time' => ['b.end_time', '>=', $nowTimeStr], // 活动报名结束时间大于当前时间
            'a.deleted' => 0,
            'b.deleted' => 0
        ];
        $contestSchoolApply = (new \app\common\model\ContestSchoolApplyModel)->alias('a')
            ->join('wechat_contest b', 'a.contest_id = b.id', 'left')
            ->join('wechat_contest_vote_settings c', 'a.contest_id = c.contest_id', 'left')
            ->where($where)
            ->field('a.id schoolApplyId, a.inst_id instId, a.domain, b.name contestName, b.school_submit_end_time schoolSubmitEndTime, c.vote_start_time voteStartTime, c.vote_end_time voteEndTime')
            ->select()
            ->toArray();
        if (count($contestSchoolApply) > 0) {
            foreach ($contestSchoolApply as $key => &$value) {
                if (strtotime(nowTimeStr()) !== strtotime($value['voteStartTime'])) continue;
                $formatAppMessageByMethod = $this->formatAppMessageByMethod(__FUNCTION__, ['contestName' => $value['contestName']]);
                VoteManager::sendAppNotice($value['domain'], $value['instId'], $formatAppMessageByMethod['userData'], $formatAppMessageByMethod['content']);
                $formatWechatMessageByMethod = $this->formatWechatMessageByMethod(__FUNCTION__, ['contestName' => $value['contestName'], 'voteStartTime' => $value['voteStartTime'], 'voteEndTime' => $value['voteEndTime']]);
                TemplateMessageService::sendMessage($formatWechatMessageByMethod['userData'], 'vateStartNotificationTemplate', $formatWechatMessageByMethod['templateData']);
            }
        }
        echo 'ok';
    }

    /**
     * 功    能:投票结束前一天通知
     */
    public function vateEndBeforeHandNotification()
    {
        set_time_limit(0);
        ini_set('memory_limit', -1);
        $nowTimeStr = nowTimeStr();
        $where = [
            'a.submit_work_status' => 1, // 学校作品已提交
            'a.publish_status' => 1, // 活动已发布
            'b.vote_open' => 1, // 投票开关已开启
            'a.deleted' => 0,
            'b.deleted' => 0
        ];
        $contestSchoolApply = (new \app\common\model\ContestSchoolApplyModel)->alias('a')
            ->join('wechat_contest b', 'a.contest_id = b.id', 'left')
            ->join('wechat_contest_vote_settings c', 'a.contest_id = c.contest_id', 'left')
            ->where($where)
            ->field('a.id schoolApplyId, a.contest_id contestId, a.inst_id instId, a.domain, a.vote_count voteCount, b.name contestName, b.school_submit_end_time schoolSubmitEndTime, c.vote_start_time voteStartTime, c.vote_end_time voteEndTime')
            ->select()
            ->toArray();
        if (count($contestSchoolApply) > 0) {
            foreach ($contestSchoolApply as $key => &$value) {
                if (strtotime($nowTimeStr) >= strtotime($value['voteEndTime'])) continue;
                $timesArr = $this->timeDifferenceCalculation(strtotime($nowTimeStr), strtotime($value['voteEndTime']));
                if ($timesArr['day'] !== 1) continue;
                $formatAppMessageByMethod = $this->formatAppMessageByMethod(__FUNCTION__, ['contestName' => $value['contestName'], 'voteCount' => $value['voteCount']]);
                VoteManager::sendAppNotice($value['domain'], $value['instId'], $formatAppMessageByMethod['userData'], $formatAppMessageByMethod['content']);
                $formatWechatMessageByMethod = $this->formatWechatMessageByMethod(__FUNCTION__, ['contestName' => $value['contestName'], 'voteCount' => $value['voteCount']]);
                TemplateMessageService::sendMessage($formatWechatMessageByMethod['userData'], 'vateEndBeforeHandNotificationTemplate', $formatWechatMessageByMethod['templateData']);
            }
        }
        echo 'ok';
    }

    /**
     * 功    能:投票结束通知
     */
    public function vateEndNotification()
    {
        set_time_limit(0);
        ini_set('memory_limit', -1);
        $nowTimeStr = nowTimeStr();
        $where = [
            'a.submit_work_status' => 1, // 学校作品已提交
            'a.publish_status' => 1, // 活动已发布
            'b.vote_open' => 1, // 投票开关已开启
            'a.deleted' => 0,
            'b.deleted' => 0
        ];
        $contestSchoolApply = (new \app\common\model\ContestSchoolApplyModel)->alias('a')
            ->join('wechat_contest b', 'a.contest_id = b.id', 'left')
            ->join('wechat_contest_vote_settings c', 'a.contest_id = c.contest_id', 'left')
            ->where($where)
            ->whereTime('end_time', '>=', $nowTimeStr)
            ->field('a.id schoolApplyId, a.contest_id contestId, a.inst_id instId, a.domain, a.vote_count voteCount, b.name contestName, b.school_submit_end_time schoolSubmitEndTime, c.vote_start_time voteStartTime, c.vote_end_time voteEndTime')
            ->order('voteCount DESC')
            ->select()
            ->toArray();
        if (count($contestSchoolApply) > 0) {
            foreach ($contestSchoolApply as $key => &$value) {
                if (strtotime($nowTimeStr) !== strtotime($value['voteEndTime'])) continue;
                $schoolRanking = intval($key + 1);
                $formatAppMessageByMethod = $this->formatAppMessageByMethod(__FUNCTION__, ['contestName' => $value['contestName'], 'schoolRanking' => $schoolRanking]);
                VoteManager::sendAppNotice($value['domain'], $value['instId'], $formatAppMessageByMethod['userData'], $formatAppMessageByMethod['content']);
                $formatWechatMessageByMethod = $this->formatWechatMessageByMethod(__FUNCTION__, ['contestName' => $value['contestName'], 'schoolRanking' => $schoolRanking, 'voteCount' => $value['voteCount']]);
                TemplateMessageService::sendMessage($formatWechatMessageByMethod['userData'], 'vateEndNotificationTemplate', $formatWechatMessageByMethod['templateData']);
            }
        }
        echo 'ok';
    }

    /**
     * 功    能:格式化 wechat 发送通知参数
     *
     * @param $method
     * @param $data
     * @return array
     */
    public function formatWechatMessageByMethod($method, $data)
    {
        switch ($method) {
            case 'workSubmissionDeadline':
                $userData = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // TODO 仅通知参加此赛事的管理员
                $templateData = [
                    'first' => '距离提交作品截止仅剩1天，请尽快前往优学堂校长通公众号活动中心审阅并提交学员活动作品',
                    'keyword1' => '名称：' . $data['contestName'] . '活动学员作品',
                    'keyword2' => '作品:提交参与学员的作品',
                    'keyword3' => '姓名：' . $data['instName'],
                    'keyword4' => '结果：请尽快前往审阅并提交学员活动作品。',
                    'remark' => '点击详情即可前往提交学员活动作品。'
                ];
                break;
            case 'vateStartNotification':
                $userData = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // TODO 仅通知参加此赛事的学校老师及管理员
                $templateData = [
                    'first' => '学校参与的投票正在火热进行，快去为您的学校投票吧~',
                    'keyword1' => '预约项目：' . $data['contestName'] . '投票',
                    'keyword2' => '预约时间：' . $data['voteStartTime'] . '-' . $data['voteEndTime'] . '内投票',
                    'remark' => '点击详情即可参与投票'
                ];
                break;
            case 'vateEndBeforeHandNotification':
                $userData = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // TODO 仅通知参加此赛事的学校老师及管理员
                $templateData = [
                    'first' => '距离投票结束仅剩 1 天，抓紧时间拉票为学校获取一个好名次吧',
                    'keyword1' => '作品名：' . $data['contestName'] . '投票',
                    'keyword2' => '统计日期：' . nowTimeStr(),
                    'keyword3' => '票数：' . $data['voteCount'],
                    'remark' => '点击详情即可参与投票'
                ];
                break;
            case 'vateEndNotification':
                $userData = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // TODO 仅通知参加此赛事的学校老师及管理员
                $templateData = [
                    'first' => '投票已结束，您的学校在此次投票中获得第' . $data['schoolRanking'] . '名',
                    'keyword1' => '作品名：' . $data['contestName'] . '投票',
                    'keyword2' => '统计日期：' . nowTimeStr(),
                    'keyword3' => '票数：' . $data['voteCount'],
                    'remark' => '点击详情即可查看投票结果'
                ];
                break;
            default:
                // ...
                break;
        }
        return ['userData' => $userData, 'templateData' => $templateData];
    }

    /**
     * 功    能:格式化 app 发送通知参数
     * @param $method string
     * @param $data array
     * @return array
     */
    public function formatAppMessageByMethod($method, $data)
    {
        $content = '';
        $userData = array();
        switch ($method) {
            case 'workSubmissionDeadline':
                $userData = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // TODO 仅通知参加此赛事的管理员
                $content = $data['contestName'] . '提交作品截止仅剩 1 天，请尽快前往学校-活动中心审阅并提交学员活动作品，立即前往>';
                break;
            case 'vateStartNotification':
                $userData = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // TODO 仅通知参加此赛事的学校老师及管理员
                $content = $data['contestName'] . '投票开始啦，快去为您的学校投票吧，前往优学堂校长通公众号活动中心参与投票。';
                break;
            case 'vateEndBeforeHandNotification':
                $userData = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // TODO 仅通知参加此赛事的学校老师及管理员
                $content = $data['contestName'] . '投票结束仅剩 1 天，抓紧时间拉票为学校获取一个好名次吧，前往优学堂校长通公众号活动中心参与投票。';
                break;
            case 'vateEndNotification':
                $userData = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // TODO 仅通知参加此赛事的学校老师及管理员
                $content = $data['contestName'] . '投票已结束，您的学校在次投票中获得第' . $data['schoolRanking'] . '名，前往优学堂校长通公众号活动中心查看详情。';
                break;
            default:
                // ...
                break;
        }
        return ['userData' => $userData, 'content' => $content];
    }

    /**
     * 计算两个时间段相差值
     * @param $begin_time TimeStamp
     * @param $end_time   TimeStamp
     * @return array
     */
    public function timeDifferenceCalculation($begin_time, $end_time)
    {
        if ($begin_time < $end_time) {
            $starttime = $begin_time;
            $endtime = $end_time;
        } else {
            $starttime = $end_time;
            $endtime = $begin_time;
        }

        $timediff = $endtime - $starttime;
        $days = intval($timediff / 86400);
        $remain = $timediff % 86400;
        $hours = intval($remain / 3600);
        $remain = $remain % 3600;
        $mins = intval($remain / 60);
        $secs = $remain % 60;
        return array('day' => $days, 'hour' => $hours, 'min' => $mins, 'sec' => $secs);
    }
}